package com.example.base_model.view

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.annotation.IdRes
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import androidx.navigation.findNavController
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.example.base_model.R
import com.example.base_model.dialog.LoadingCallback
import com.example.base_model.dialog.LoadingManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

/**
 * @Author jiangKunKun
 * @CreateDate 2025/6/23
 * @Description
 * @SpittingGrooves
 */

abstract class BaseActivity<VD : ViewDataBinding> : AppCompatActivity(), LoadingCallback {
    protected lateinit var mBinding: VD

    /**
     * 当前上下文实例
     */
    protected lateinit var mActivity: Activity
    override fun onCreate(@Nullable savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mActivity = this
        LogUtils.d("当前Activity是${packageName}${localClassName}")
        KeyboardUtils.hideSoftInput(this)
        ScreenUtils.setFullScreen(this)
        // 之前要做的
        beforeSetContent()
        mBinding = DataBindingUtil.setContentView(this, attachLayoutRes())
        // 主要传递 savedInstanceState
        init(savedInstanceState)
        // 初始化各种监听
        initObservers()
        // 初始化点击事件
        initClickEvents()
        // 初始化基础数据
        initData()
    }

    /**
     * 之前要做的
     */
    protected open fun beforeSetContent() {}

    /**
     * 主要传递 savedInstanceState
     */
    protected open fun init(savedInstanceState: Bundle?) {}

    /**
     * 初始化各种监听
     */
    protected abstract fun initObservers()

    /**
     * 初始化点击事件
     */
    protected abstract fun initClickEvents()

    /**
     * 初始化基础数据
     */
    protected abstract fun initData()

    /**
     * 初始化布局
     */
    protected abstract fun attachLayoutRes(): Int

    /**
     * 显示加载
     */
    override fun showLoading(msg: String) {
        LoadingManager.showLoading(this, msg)
    }

    /**
     * 关闭加载
     */
    override fun hideLoading() {
        LoadingManager.dismissLoading()
    }

    /**
     * UI 更新：使用 Lifecycle.State.STARTED - 界面可见时更新 UI
     * 高精度任务：使用 Lifecycle.State.RESUMED - 前台运行时执行
     * 后台任务：考虑使用 Lifecycle.State.CREATED，但需谨慎评估需求
     */
    protected inline fun launchAndCollect(crossinline block: suspend CoroutineScope.() -> Unit) {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                block()
            }
        }
    }

    /**
     * 可选传入任意 Lifecycle.State
     * UI 更新：使用 Lifecycle.State.STARTED - 界面可见时更新 UI
     * 高精度任务：使用 Lifecycle.State.RESUMED - 前台运行时执行
     * 后台任务：考虑使用 Lifecycle.State.CREATED，但需谨慎评估需求
     */
    protected inline fun launchAndCollect(state: Lifecycle.State, crossinline block: suspend CoroutineScope.() -> Unit) {
        lifecycleScope.launch {
            repeatOnLifecycle(state) {
                block()
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (::mBinding.isInitialized) {
            mBinding.unbind()
        }
    }

    /**
     * 页面跳转
     */
    fun goActivity(cls: Class<*>) {
        startActivity(Intent(this, cls))
    }

    /**
     * 页面跳转携带参数
     */
    fun goActivity(cls: Class<*>, bundle: Bundle) {
        val intent = Intent(this, cls)
        intent.putExtras(bundle)
        startActivity(intent)
    }

    /**
     * 重置配置 fontScale：保持字体比例不变，始终为 1.
     */
    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(newBase)
        overrideFontScale(newBase)
    }
    /**
     * 重置配置 fontScale：保持字体比例不变，始终为 1.
     */
    private fun overrideFontScale(context: Context) {
        val configuration = context.resources.configuration
        configuration.fontScale = 1f
        applyOverrideConfiguration(configuration)
    }
}